﻿package Gameplay.GridContent 
{	
	import Common.UnitAbstract;		
	import fl.motion.AdjustColor;
	import flash.filters.ColorMatrixFilter;
	import Gameplay.Constants;
	import Gameplay.ShipDirection;
	import Gameplay.GridContent.ContentAbstract;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Point;
	
	public class ShipView extends ContentAbstract
	{		
		protected var FOrientation:int;
		protected var FBitmap:Bitmap;
		protected var FOffset:Point;
		
		public function ShipView(ASource:UnitAbstract):void
		{
			super(ASource);			
			FOrientation = ShipDirection.XPlus;
			FOffset = FSource.OffsetAt(FOrientation);
			UpdateGraphic();
		}		
		
		public function get Size():int 
		{
			return FSource.Size;
		}
		
		public function get Orientation():int 
		{
			return FOrientation;
		}
		
		public function set Orientation(AOrientation:int):void 
		{
			if (AOrientation != FOrientation)
			{
				FOrientation = AOrientation;
				FOffset = FSource.OffsetAt(FOrientation);
				UpdateGraphic();
			}
		}
		
		override protected function UpdateGraphic():void
		{
			if (FBitmap)
			{
				if (FBitmap.parent)
					FBitmap.parent.removeChild(FBitmap);
				FBitmap.bitmapData.dispose();
				FBitmap = null;
			}			
			var vClass:Class = FSource.GraphicAt(FOrientation);
			FBitmap = new Bitmap(BitmapData(new vClass()));
			FBitmap.smoothing = true;
			var vColor:AdjustColor = new AdjustColor();
			vColor.brightness = 0;
			vColor.contrast = 0;
			vColor.saturation = 0;
			vColor.hue = Math.random() * 200 - 100;
			var vFilter:ColorMatrixFilter = new ColorMatrixFilter(vColor.CalculateFinalFlatArray());
			FBitmap.filters = [vFilter];
		}
		
		override public function Update():void
		{			
			FBitmap.scaleX = FBitmap.scaleY = (FField.Size / Constants.DEFAULT_SHIPS_FIELD_SIZE) * FSource.Scale;			
			FBitmap.x = FCell.x - FOffset.x * FBitmap.scaleX / FSource.Scale;
			FBitmap.y = FCell.y - FOffset.y * FBitmap.scaleY / FSource.Scale;
			
			if(FBitmap.parent != FField.UnitsLayer)
				FField.UnitsLayer.addChild(FBitmap);
		}
	}
}